﻿// owner 蒋家伟

#include "ProgressBar.h"

// qt
#include <QPainter>
#include <QBrush>
#include <QGuiApplication>

//jsdk
#include "Dbg_Warn_Define.h"

using namespace jsdk;

jsdk::ProgressBar::ProgressBar(bool isAsynCalled, const QColor& color) :
    m_backgroundColor(color),
    m_present(0),
    m_isAsynCalled(isAsynCalled),
    m_fontColor(QColor(0,0,0))
{
    this->setWindowFlag(Qt::Window);
    this->setWindowFlag(Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setFixedSize(150, 150);
}

OwnerPtr<jsdk::ProgressBar> jsdk::ProgressBar::create(bool isAsynCalled , const QColor* pColor)
{
    if (pColor)
    {
        return NEW_AS_OWNERPTR(jsdk::ProgressBar, isAsynCalled, *pColor);
    }
    else
    {
        return NEW_AS_OWNERPTR(jsdk::ProgressBar, isAsynCalled, QColor(0, 0, 255));
    }
}

void jsdk::ProgressBar::setPresent(uint8_t present)
{
    DBG_WARN_AND_RETURN_VOID_UNLESS(present >= 0 && present <= 100, L"当前百分比无效，应该在0-100之间", L"蒋家伟", L"2023-09-15");
    m_present = present;
    update();
    if(!m_isAsynCalled)
        qApp->processEvents();
}

void jsdk::ProgressBar::setFixedSize(uint16_t width, uint16_t height)
{
    QWidget::setFixedSize(width, height);
}

void jsdk::ProgressBar::show()
{
    QWidget::show();
}

void jsdk::ProgressBar::close()
{
    QWidget::close();
}

void jsdk::ProgressBar::setPrefix(const std::wstring& prefix)
{
    m_prefix = prefix;
}

void jsdk::ProgressBar::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.fillRect(this->rect(), QBrush());

    int angle = static_cast<int>(360.0 * m_present / 100);

    int side = std::min(this->width(), this->height());
    QRectF outRect(0, 0, side, side);
    QRectF inRect(10, 10, side-20, side-20);
    QString valueStr = QString::fromStdWString(m_prefix) + QString("%1%").arg(QString::number(m_present));

    painter.setPen(Qt::NoPen);

    QColor progressColor = m_backgroundColor;
    progressColor.setAlpha(100);
    // 底部圆
    painter.setBrush(QBrush(progressColor));
    painter.drawEllipse(outRect);

    // 进度条
    painter.setBrush(QBrush(m_backgroundColor));
    painter.drawPie(outRect, (90 - angle) * 16, angle * 16);

    // 中心圆
    painter.setBrush(QColor(255, 255, 255));
    painter.drawEllipse(inRect);

    QFont front("Microsoft YaHei", m_fontWidth, QFont::Normal);
    painter.setFont(front);
    painter.setPen(QColor(m_fontColor));
    painter.drawText(inRect, Qt::AlignCenter, valueStr);

    QWidget::paintEvent(event);
}
